<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
    width="600px"
    @close="reset"
  >
    <el-form 
      ref="articleFormRef"
      :model="tableItem" 
      :rules="rules"
      label-width="100"
      label-position="top"
      :disabled="!isDisabled"
    >

      <el-form-item label="项目" prop="projectId">
        <el-select 
          v-model="tableItem.projectId" 
          :disabled="dialogStatus=='edit'" 
          placeholder="选择一个项目"
          @change="handleChange"
        >
          <el-option 
            v-for="item in projectList"
            :label="item.projectName" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>

      <el-form-item label="房间号" prop="houseIdList">
        <el-select  
          v-model="tableItem.houseIdList" 
          :disabled="dialogStatus==='edit'"
          multiple
          placeholder="选择房间"
        >
          <el-option 
            v-for="item of homeNumList"
            :label="item.houseNum" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>

      <el-form-item label="收费模板" prop="templateId">
        <el-select v-model="tableItem.templateId" placeholder="选择一个收费模板">
          <el-option 
            v-for="item of templateList"
            :label="item.templateName" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>

      <el-form-item label="结算方式:" prop="settleType">
        <el-radio-group v-model="tableItem.settleType">
          <el-radio :value="1">预付费</el-radio>
          <el-radio :value="2">后付费</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账单日期" prop="billDay">
        <el-input-number
          v-model="tableItem.billDay"
          :controls="false" 
          placeholder="请输入"
          type="number" 
          min="3"
           max="7"
        >
          <template #prepend>每月</template>
          <template #append>日</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="欠费宽限期" prop="overdueGrace">
        <el-input-number
          v-model="tableItem.overdueGrace"
          :controls="false" 
          placeholder="请输入"
        >
          <template #append>天</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="tableItem.remark" />
      </el-form-item>

    </el-form>
    <template #footer v-if="isDisabled">
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="isSubmitting"
          :disabled="isSubmitting"
          @click="dialogStatus==='create'?createData():updateData()"
        >确 定</el-button>
      </span>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, inject,watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addCharge, editCharge,getHouseIdList, homeNumList, getChargeTemplateList } from '@/api/settle'
import { validate } from '@/utils/validate'

const projectList = inject('projectList')
console.log('projectList', projectList)

// 收费模板相关
const templateList = ref([])
const getTemplateList = async () => { 
  const res = await getChargeTemplateList()
  templateList.value = res.data
}

getTemplateList()

const isDisabled = ref(true)
const isSubmitting = ref(false)

const tableItem = reactive({
  projectId: null,
  houseIdList: [],
  templateId: '',
  settleType: null,
  billDay: null,
  overdueGrace: null,
  remark: '',
})

const rules = reactive({
  projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
  houseIdList: [{ required: true, message: '请选择房间', trigger: 'change' }],
  templateId: [{ required: true, message: '请选择收费模板', trigger: 'change' }],
  settleType: [{ required: true, message: '请选择结算方式', trigger: 'change' }],
  billDay: [{ required: true, message: '请输入账单日期', trigger: 'blur' }],
  overdueGrace: [{ required: true, message: '请输入欠费宽限期', trigger: 'blur' }]
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const reset = () => {
  if (!articleFormRef.value) return
  articleFormRef.value.resetFields()
  Object.assign(tableItem, {
    projectId: null,
    houseIdList: [],
    templateId: '',
    settleType: null,
    billDay: null,
    overdueGrace: null,
    remark: '',
  })
}

const handleChange = () => {
  tableItem.houseIdList = []
}

const articleFormRef = ref(null)

const emit = defineEmits(['listChange'])

const createData = async () => {
  if (isSubmitting.value) return
  
  try {
    isSubmitting.value = true
    const valid = await validate(articleFormRef)
    if (!valid) {
      ElMessage.warning('请检查表单填写是否完整')
      return
    }
    
    const response = await addCharge(tableItem)
    if (response.code === 200) {
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建成功！')
    } else {
      ElMessage.error(response.msg || '创建失败！')
    }
  } catch (error: any) {
    console.error('创建失败:', error)
    ElMessage.error(error.msg || '创建失败！')
  } finally {
    isSubmitting.value = false
  }
}

const updateData = async () => {
  if (isSubmitting.value) return
  
  try {
    isSubmitting.value = true
    const valid = await validate(articleFormRef)
    if (!valid) {
      ElMessage.warning('请检查表单填写是否完整')
      return
    }
    
    const response = await editCharge(tableItem)
    if (response.code === 200) {
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('更新成功！')
    } else {
      ElMessage.error(response.msg || '更新失败！')
    }
  } catch (error: any) {
    console.error('更新失败:', error)
    ElMessage.error(error.msg || '更新失败！')
  } finally {
    isSubmitting.value = false
  }
}

defineExpose({ dialogVisible, isDisabled, tableItem, dialogStatus, reset })
// 房间号相关
const homeNumList = ref<homeNumList>([])
const getHomeNumList = async (v: number) => { 
  const res = await getHouseIdList(v)
  homeNumList.value = res.data
}
watch(() => (tableItem.projectId as unknown as number), getHomeNumList)

</script>
<style lang="scss" scoped>
</style>
